<?php
	$subdirname = $argv[1];
	$movtypes	= array("mov","avi","mpg","mpeg","divx","ogm","mp4","mkv","m4v","mp4v");	// What are movie file extensions
	$subdir = opendir($subdirname);

		$xml		= array();
		$xmlfile	= false;
		$cover		= false;
		$subtitles	= false;
		$listavi	= array();
		$listavism	= array();
		$sample		= "";
		$trailer	= "";
		$movcount	= 0;
		$xmlcount	= 0;
		$jpgcount	= 0;
		$srtcount	= 0;
		$nfofile	= "";

		while(false !== ($file = readdir($subdir))){
			if(substr($file,0,1) == "."){ continue; }				// No hidden files / dirs
			$ext = strtolower(substr($file, strrpos($file, ".")+1));
			if($ext == ""){ continue; }
			if(in_array($ext, $movtypes)){							// It is a movie
				$movcount++;
				if(strpos($file, "samp") > 0){						// It is a sample
					$sample = $file;
				}elseif(strpos($file, "trailer") > 0){				// It is a trailer
					$trailer = $file;
				}else{												// It is a part of the movie
					array_push($listavism, substr($file, 0, strrpos($file, ".")));
					array_push($listavi, $file);
					if($filesize == 0){								// Get file size of first movie, for subtitle downloading...
						$filesize = filesize($subdirname."/".$file);
					}
				}
			}
		}
		
		if($argv[2] == "cover.jpg"){
			; // Cover is there already... just copy it
		}else{
			$cover = file($argv[2]);
			$coverfile = fopen($subdirname."cover.jpg","w");
			fwrite($coverfile, implode("",$cover));
			fclose($coverfile);
		}
		
	// Wegschrijven...
	
	sort($listavi);
	$i = 0;
	foreach($listavi as $avi){
		$ext = strtolower(substr($avi, strrpos($avi, ".")+1));
		copy($subdirname."cover.jpg", $subdirname.str_replace(".".$ext,".jpg",$avi));
	}
	if($sample != ""){
		$ext = strtolower(substr($sample, strrpos($sample, ".")+1));
		copy($subdirname."cover.jpg", $subdirname.str_replace(".".$ext,".jpg",$sample));
	}
	if($trailer != ""){
		$ext = strtolower(substr($trailer, strrpos($trailer, ".")+1));
		copy($subdirname."cover.jpg", $subdirname.str_replace(".".$ext,".jpg",$trailer));
	}
	echo '1';
?>
